package com.sntra.beibi.runner;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.formats.png.PngImageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.sntra.beibi.common.DotUtils;
import com.sntra.beibi.dao.BookMapper;
import com.sntra.beibi.dao.LearnPageMapper;
import com.sntra.beibi.dao.PageMapper;
import com.sntra.beibi.domain.Book;
import com.sntra.beibi.domain.Dot;
import com.sntra.beibi.domain.LearnPage;
import com.sntra.beibi.domain.Page;
import com.sntra.beibi.service.DotService;
import com.sntra.beibi.service.PenService;

@Component
public class DotsTask {
	
    private Logger logger = LoggerFactory.getLogger(getClass());
    private int i;
    
    @Autowired
    private BookMapper bookMapper;
    
    @Autowired
    private PageMapper pageMapper;
    
    @Autowired
    private LearnPageMapper lpMapper;
    
    @Autowired
	private DotService dotService;

	@Autowired
	private PenService mPen;
	
	@Value("${doc.rootdir}")
	private String dir;
	
	@Value("${img.rootdir}")
	private String imgDir;
	    
	//@Scheduled(cron = "0 */3 * * * ?")
    public void generateImgs() {
		LearnPage p = new LearnPage();
		p.setImgStatus(0);
    	List<LearnPage>  lps = lpMapper.queryPages(p);
    	for(LearnPage lp : lps) {
    		if(lp!=null && StringUtils.hasText(lp.getUrl())) {
                String pdfUrl = lp.getUrl();
                String imgUrl = pdfUrl.replace(dir, imgDir);
                File ifp = new File(imgUrl);
                imgUrl = ifp.getParent();
                imgUrl = DotUtils.pdf2Image(pdfUrl, imgUrl, 105);
                lp.setImgStatus(1);
                lp.setImgUrl(imgUrl);
                lpMapper.updateImgStatus(lp);
        	}
    	}
    }
	
    @Scheduled(cron = "0 */3 * * * ?")
    public void drawBook() {
    	List<Book> books = bookMapper.queryUngenerateBooks();
    	
    	try {
    		for(Book b : books) {
    		   String filePath = b.getFilePath();
    		   File pf = new File(filePath);
    		   PdfReader reader = new PdfReader(pf);
   			   PdfDocument pdf = new PdfDocument(reader);
   			   int pnum = pdf.getNumberOfPages();
   			   String pdir = pf.getParent();
		    	for(int p=0; p<pnum; p++) {
	    			String url = pdir + "/"+ (p+1)  +".pdf";
	    			PdfWriter writer = new PdfWriter(new File(url));
	    			PdfDocument pagePdf = new PdfDocument(writer);
	    			PdfPage pp = pdf.getPage(p+1);
	    			pagePdf.addPage(pp.copyTo(pagePdf));
	    			pagePdf.close();
	    			Date now = new Date();
                    Page page = new Page();
	    	        page.setBookId(b.getId());
	    	        page.setName((b.getTitle().length()>5?b.getTitle().substring(0, 6):b.getTitle())+"第"+(p+1) +"页");
	    	        page.setUrl(url);
	    	        String imgUrl = pdir.replace(dir, imgDir);
	    	        imgUrl = DotUtils.pdf2Image(url, imgUrl, 300);
	    	        page.setImgStatus(1);
	    	        page.setImgUrl(imgUrl);
	    	        page.setPageNo(p);
	    	        page.setDoStatus(1);
	    	        page.setCreateTime(now);
	    	        page.setUpdateTime(now);
	    	        pageMapper.insert(page);
		    	}
		    	pdf.close();
		    	b.setGenStatus(1);
	    	    bookMapper.updateGenStatus(b);
    		}
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        logger.info("thread id:{},FixedPrintTask execute times:{}", Thread.currentThread().getId(), ++i);
    }
	
    //@Scheduled(cron = "0 19 19 * * ? ")
    public void initData() {
    	Book book = new Book();
    	book.setTitle("记事本");
    	int id = 100;
    	book.setId(100);
    	book.setIntroduction("tql示例本子");
    	
    	File bookDir = new File(dir+id); 
    	try {
    		if(!bookDir.exists()) {
    			bookDir.mkdirs();
    		}
			/*
			 * String bookUrl = bookDir + "\\" + id + ".pdf"; PdfWriter bookWriter = new
			 * PdfWriter(new File(bookUrl)); PdfDocument bookPdf = new
			 * PdfDocument(bookWriter); PdfFont font =
			 * PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
			 */
	    	for(int p=0; p<64; p++) {
	    		PdfReader reader = new PdfReader(new File(dir + "test.pdf"));
    			String url = dir + id +"\\"+ p +".pdf";
    			PdfWriter writer = new PdfWriter(new File(url));
    			PdfDocument pdf = new PdfDocument(reader, writer);
    			
    			PdfPage pp = pdf.getFirstPage();
    			Rectangle pageSize = pp.getPageSize();
    			float width = pageSize.getWidth();
    			
    			PdfCanvas canvas = new PdfCanvas(pp);
                canvas.beginText().setFontAndSize(PdfFontFactory.createFont(StandardFonts.SYMBOL), 18);
                      
                if (p % 2 == 0) {
                	canvas.moveText(width - 90, 40);
                } else {
                	canvas.moveText(90,  40);
                }
                canvas.newlineShowText(String.format("%02d", p + 1));
                canvas.endText();
    			Date now = new Date();
    			canvas.stroke();
    	        pdf.close();
    	        Page page = new Page();
    	        page.setBookId(id);
    	        page.setName("笔记本第"+(p+1) +"页");
    	        page.setUrl(url);
    	        page.setPageNo(p);
    	        page.setCreateTime(now);
    	        page.setUpdateTime(now);
    	        pageMapper.insert(page);
    	        
				/*
				 * PdfReader pr = new PdfReader(new File(url)); PdfDocument pdr = new
				 * PdfDocument(pr); PdfPage ppp = pdr.getFirstPage(); pdr.copyPagesTo(0, 1,
				 * bookPdf); pdr.close();
				 */
	    	}
	    	//bookPdf.close();
	    	book.setFilePath(dir);
	    	bookMapper.insert(book);
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        logger.info("thread id:{},FixedPrintTask execute times:{}", Thread.currentThread().getId(), ++i);
    }
    
    //@Scheduled(cron = "0 43 15 * * ? ")
    public void exeDraw() {
    	List<LearnPage>  lps = lpMapper.selectPages(0);
    	for(LearnPage lp : lps) {
    		draw(lp);
    	}
    }
    
    private String draw(LearnPage lp) {
		int ownerId = lp.getLearnerId(); 
		int bookId = lp.getBookId();
		int pageNo = lp.getPageNo();
		String url = lp.getUrl();
    	PdfDocument pdf = null;
    	
		try {
			if(!StringUtils.hasText(url)) {
	    		List<Page> ps = pageMapper.pageOfId(lp.getPageId());
	    		url = ps.get(0).getUrl();
	    		PdfReader reader = new PdfReader(new File(url));
	    		String learnUrl = dir + bookId + "\\" + ownerId + "\\" + pageNo + ".pdf";
	    		lp.setUrl(learnUrl);
				PdfWriter writer = new PdfWriter(new File(learnUrl));
				pdf = new PdfDocument(reader, writer);
	    	} else {
	    		PdfWriter writer = new PdfWriter(new File(url));
				pdf = new PdfDocument(writer);
	    	}
			PdfPage pp = pdf.getFirstPage();
			Rectangle pageSize = pp.getPageSize();
			float height =  pageSize.getHeight();
			float width = (int) pageSize.getWidth();
			
			File file = new File(dir + "pager_positive.png");
			PngImageInfo  imageInfo = (PngImageInfo)Imaging.getImageInfo(file);
			float w = imageInfo.getPhysicalWidthInch() * DotUtils.IN_SIZE; 
			float dpi = imageInfo.getPhysicalHeightDpi();
			
			PdfCanvas canvas = new PdfCanvas(pp);
			mPen.transformWidth(1.0f, dpi);
	        
            float paperHeight = imageInfo.getPhysicalHeightInch() * DotUtils.IN_SIZE; 
            
			List<Dot> dots = dotService.selectDotsByUser(ownerId, bookId, pageNo, 0);
			List<Integer> dotIds = new ArrayList<Integer>();
            for(Dot dot : dots) {
            	mPen.processDot(dot, (int)height, paperHeight, canvas, width, height);
            	dotIds.add(dot.getDotId());
            }
            dotService.updateStatusBatch(dotIds);
			canvas.stroke();
	        pdf.close();
	        lp.setDoStatus(1);
	        lpMapper.updateStatusAndUrl(lp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "OK";
	}

    //@Scheduled(cron = "*/5 * * * * ?")
    public void execute() {
        logger.info("thread id:{},FixedPrintTask execute times:{}", Thread.currentThread().getId(), ++i);
    }

}
